import React, { FC, useState, useCallback, useEffect, useRef } from 'react';
import i18n from 'i18n-js';
import { toJS, reaction } from 'mobx';
import { View, Text, Image } from '@tarojs/components';
import Toast from '@/utils/Toast';
import { formattingNumByLength } from '@/utils';
import regular from '@/utils/regular';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import InputAlert from '@/components/Alert/inputAlert';
import deviceDataModal from '@/models/deviceData';
import deviceListModal from '@/models/deviceList';
import gizwitsSdkModal from '@/models/gizwitsSdk';
import { isSupportPasswordVerify, getItemForPk } from '@/config/product';
import { getDevicePassword, saveDevicePassword } from './passwordStorage';

interface IProps {
  device: IDevice;
}

interface IState {
  alertShow: boolean;
}

const passwordSwitchKey = 'password_power';
const passwordKey = 'password';
const passwordControlKey = 'password_control';


// 1分钟不验证会超时
const verifyPasswordTime = 1 * 60 * 1000;

// 验证超过5次失败，跳出设备控制页面
const maxFailCount = 5;

class DevicePasswordVerifyModal extends React.Component<IProps, IState> {

  isNeedVerify: boolean;
  inputPassword: string;
  deviceListReaction: any;
  deviceDataReaction: any;
  failCount: number;
  netStatus: number;
  deviceId: string;
  timer: any;
  data: any;
  verified: boolean;
  isAutoVerify: boolean;

  constructor(props: IProps) {
    super(props);
    const { device } = props;
    const conifg = getItemForPk(device.productKey);
    console.log('conifg', conifg);
    this.isNeedVerify = !!conifg && isSupportPasswordVerify(conifg);
    this.state = {
      alertShow: false,
    };
    this.timer = null;
    this.deviceId = device.deviceId;
    this.netStatus = device.netStatus;
    this.inputPassword = ''; // 记录用户输入的密码
    this.data = undefined;
    this.verified = false; // 是否已经校验过了
    this.failCount = 0; // 密码校验失败次数
    this.isAutoVerify = false; // 是否是自动验证密码
  }

  componentDidMount() {
    // 进入模板是会自动获取一次设备状态的，所以这里不去主动获取
    const { device } = this.props;
    if (device && device.netStatus === 2) {
      const data = deviceDataModal.data[device.deviceId];
      console.log('componentDidMount', deviceDataModal.data);
      if (data && data.data) {
        this.data = data.data;
        this.checkNeedShowAlert();
      } else {
        console.log('checkNeedShowAlert getDeviceStatus');
        gizwitsSdkModal.getDeviceStatus({ device });
      }
    }

    this.deviceListReaction = reaction(
      () => {
        return {
          list: toJS(deviceListModal.data)
        };
      },
      ({ list }: any) => {
        const targetDevice = list.find((item: any) => item.deviceId === this.deviceId);
        if (targetDevice && !this.verified && targetDevice.netStatus == 2 && this.netStatus !== targetDevice.netStatus) {
          // 如果设备在之后才上线，那就获取一次状态先
          gizwitsSdkModal.getDeviceStatus({ device: targetDevice });
        }
      },
      {
        fireImmediately: true,
        delay: 800,
        equals: (a, b) => {
          if (
            a !== b
            || a.list !== b.list
            || a.list.length !== b.list.length
            || a.bleDeviceList !== b.bleDeviceList
            || a.bleDeviceList.length !== b.bleDeviceList.length
          ) {
            return false;
          }
          for (let i = 0; i < b.list.length; i++) {
            if (a.list[i] !== b.list[i]) {
              return false;
            }
          }
          for (let i = 0; i < b.bleDeviceList.length; i++) {
            if (a.bleDeviceList[i] !== b.bleDeviceList[i]) {
              return false;
            }
          }
          return true;
        },
      });

    this.deviceDataReaction = reaction(
      () => {
        return {
          deviceData: toJS(deviceDataModal.data),
        };
      },
      ({ deviceData }: any) => {
        const { device: dDevice } = this.props;
        if (!this.verified && dDevice && dDevice.netStatus === 2) {
          const data = deviceData[this.deviceId];
          if (data && data.data) {
            this.data = data.data;
            this.checkNeedShowAlert();
          }
        }
      },
      {
        fireImmediately: true,
        delay: 800,
        equals: (a, b) => {
          if (
            a !== b
            || a.deviceData !== b.deviceData
          ) {
            return false;
          }
          return true;
        },
      }
    );
  }

  componentWillUnmount() {
    this.failCount = 0;
    this.verified = false;
    this.deviceListReaction();
    this.deviceDataReaction();
    this.clearTimer();
  }

  checkNeedShowAlert = async () => {
    console.log('checkNeedShowAlert', this.verified);
    if (this.data && this.isNeedVerify) {
      const devicPasswordControlPassword = this.data[passwordControlKey];
      if (devicPasswordControlPassword) {
        this.verified = true;
        const devicePasswordSwitch = this.data[passwordSwitchKey];
        console.log('checkNeedShowAlert', devicePasswordSwitch);
        if (devicePasswordSwitch) {
          const { device } = this.props;
          // 如果本地有记录是验证过的，就拿本地先校验
          this.inputPassword = await getDevicePassword(device);
          if (this.inputPassword) {
            this.isAutoVerify = true;
            this.verifyPassword();
          } else {
            this.showAlert();
          }
        }
      }
    }
  }

  // 验证密码最终都走这个方法
  verifyPassword = () => {
    if (this.data) {
      const devicePassword = this.data[passwordKey];
      console.log('verifyPassword', devicePassword);
      const passord = formattingNumByLength(devicePassword, 6);
      console.log('dPassword', devicePassword, passord, this.inputPassword);
      if (passord === this.inputPassword) {
        // 密码校验成功
        const { device } = this.props;
        saveDevicePassword({ device, password: this.inputPassword });
        this.clearTimer();
      } else if (this.isAutoVerify) {
        this.showAlert();
      } else {
        Toast.error(i18n.t('PASSWORD_ERROR'));
        this.failCount++;
        if (this.failCount >= maxFailCount) {
          // 超出次数，跳出页面
          // this.onCancel();
          this.verifyPasswordTimeOut();
        } else {
          Toast.error(i18n.t('PASSWORD_ERROR'));
          this.showAlert();
        }
      }
    }
  }

  clearTimer = () => {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }

  startTimer = () => {
    this.clearTimer();
    this.timer = setTimeout(this.verifyPasswordTimeOut, verifyPasswordTime);
  }

  verifyPasswordTimeOut = (time = 600) => {
    this.clearTimer();
    this.onCancel();
    setTimeout(() => {
      Toast.error(i18n.t('PASSWORD_VERIFY_TIMEOUT_TIP'));
    }, time);
  }

  onChangeTextNoti = () => {
    // 有输入的话，就重新计算超时
    this.startTimer();
  }

  showAlert = () => {
    this.setState({ alertShow: true }, this.startTimer);
  }

  hideAlert = (cb?: any) => {
    this.setState({ alertShow: false }, cb);
  }

  onCancel = () => {
    // 取消的话，就后退
    this.hideAlert();
    deviceDataModal.allBackToHome();
    // getData('navigation').dispatch(NavigationActions.back());
  }

  onConfirm = async (password: string) => {
    this.isAutoVerify = false;
    this.inputPassword = password;
    this.hideAlert(() => {
      if (this.inputPassword) {
        this.verifyPassword();
      } else {
        Toast.info(i18n.t('PLEASE_INPUT_PASSWORD'));
        setTimeout(() => {
          this.showAlert();
        }, 200);
      }
    });
  }

  render() {
    const { alertShow } = this.state;
    const { device } = this.props;
    console.log(this.isNeedVerify, alertShow, device, device.netStatus == 2)
    return (<View>
      <InputAlert
        maxLength={6}
        keyboardType='number'
        regular={regular.number}
        visible={this.isNeedVerify && alertShow && device && device.netStatus == 2}
        title={i18n.t('PLEASE_INPUT_PASSWORD')}
        subTitle={i18n.t('DEVICE_HAVE_PASSWORD_TIP')}
        placeholder={i18n.t('PLEASE_INPUT_PASSWORD')}
        onCancel={this.onCancel}
        onConfirm={this.onConfirm}
        onChangeTextNoti={this.onChangeTextNoti}
      />
    </View>)
  }

}

export default DevicePasswordVerifyModal;
